﻿

using System;
using AutoMapper;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

using Oliving.Edge.AuthHelper;
using Oliving.Edge.Model;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IServices;
using Oliving.Edge.Model.Dto;
using System.Linq.Expressions;
using Oliving.Edge.Common.Extensions;
using Oliving.Edge.Common.HttpRestSharp;

namespace Oliving.Edge.Controllers
{
    [ApiController]
    [Route("api/DTSN_TongDao")]
    [Authorize(Permissions.Name)]
    public class DTSN_TongDaoController : OlivingControll
    {
        IMapper _mapper;
        private readonly IDTSN_TongDaoServices _DTSN_TongDaoServices;
        private readonly IDTSN_ShangWeiJiServices _IDTSN_ShangWeiJiServices;
        private readonly ILogger<DTSN_TongDaoController> _logger;


        public DTSN_TongDaoController(
                IHttpContextAccessor accessor, PermissionRequirement requirement,
                IMapper mapper, ILogger<DTSN_TongDaoController> logger,
                IDTSN_TongDaoServices DTSN_TongDaoServices,
                IDTSN_ShangWeiJiServices IDTSN_ShangWeiJiServices
            ) : base(accessor, requirement)
        {
            _logger = logger;
            _mapper = mapper;
            _DTSN_TongDaoServices = DTSN_TongDaoServices;
            _IDTSN_ShangWeiJiServices = IDTSN_ShangWeiJiServices;
        }



        [HttpGet]
        [AllowAnonymous]
        [Route("/api/[controller]/Get")]
        public async Task<MessageModel<DTSN_TongDaoDto>> Get(int id)
        {
            var data = new MessageModel<DTSN_TongDaoDto>();
            DTSN_TongDao model = await _DTSN_TongDaoServices.QueryById(id);
            if (model == null)
            {
                data.response = null;
                data.msg = "数据不存在！";
                data.success = false;
            }
            else
            {
                var dto = _mapper.Map<DTSN_TongDaoDto>(model);
                data.response = dto;
                data.msg = "获取成功！";
                data.success = true;
            }
            return data;
        }




        [HttpGet]
        [Route("/api/[controller]/GetPageList")]
        public async Task<MessageModel<PageModel<DTSN_TongDaoPageDto>>> GetPageList(
             int page = 1, int pageSize = 20,
            string sidx = "", string order = "",
            string key = "")
        {
            Expression<Func<DTSN_TongDao, bool>> whereExpression = Td => Td.TD_State > -1;
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            else
            {
                whereExpression = whereExpression.And(Td => Td.TD_Name.Contains(key) || Td.TD_Code.Contains(key));
            }

            string colOrder = "";
            if (!string.IsNullOrEmpty(sidx))
            {
                if (order.Contains("desc"))
                {
                    order = " desc";
                }
                else
                {
                    order = " asc";
                }

                colOrder = sidx + " " + order;
            }

            var data = await _DTSN_TongDaoServices.QueryPageList(whereExpression, page, pageSize, colOrder);

            return new MessageModel<PageModel<DTSN_TongDaoPageDto>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };
        }


        [HttpPut]
        [AllowAnonymous]
        [Route("/api/[controller]/UpdateWLCode")]
        // [FromBody]
        public async Task<MessageModel<string>> UpdateWLCode([FromBody] DTSN_TongDaoDto dto)
        {
            var data = new MessageModel<string>();

            if (dto != null && dto.TD_ID > 0)
            {
                DTSN_TongDao model = await _DTSN_TongDaoServices.QueryById(dto.TD_ID);
                if (model != null)
                {

                    model.TD_WuLiao = dto.TD_WuLiao;
                    model.TD_WuLiaoCode = dto.TD_WuLiaoCode;


                    data.success = await _DTSN_TongDaoServices.Update(model);

                    if (data.success)
                    {
                        data.msg = "更新成功";
                        data.response = dto.TD_ID.ObjToString();

                        #region 调用上位机接口更新上位机通道数据

                        //// 调用上位机接口更新上位机通道数据
                        //// /API/PC/RESET
                        DTSN_ShangWeiJi swj = await _IDTSN_ShangWeiJiServices.QueryById(dto.TD_ShangWeiji);
                        string swhApi = $"http://{swj.SWJ_IP}:{swj.SWJ_Port}/";
                        var obj = HttpHelper.GetApi(swhApi, "API/PC/RESET", "code=" + model.TD_WuLiaoCode);

                        #endregion


                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "参数异常，您要更新的数据不存在";
                }
            }
            else
            {
                data.success = false;
                data.msg = "参数异常";
            }
            return data;
        }



        [HttpPut]
        [Route("/api/[controller]/Update")]
        public async Task<MessageModel<string>> Update([FromBody] DTSN_TongDaoDto dto)
        {
            var data = new MessageModel<string>();

            if (dto != null && dto.TD_ID > 0)
            {
                DTSN_TongDao model = await _DTSN_TongDaoServices.QueryById(dto.TD_ID);
                if (model != null)
                {
                    model.TD_Name = dto.TD_Name;
                    model.TD_Code = dto.TD_Code;
                    model.TD_Remark = dto.TD_Remark;
                    model.TD_CreateTime = dto.TD_CreateTime;
                    model.TD_Type = dto.TD_Type;
                    model.TD_State = dto.TD_State;
                    model.TD_WuLiao = dto.TD_WuLiao;
                    model.TD_WuLiaoCode = dto.TD_WuLiaoCode;
                    model.TD_Weight = dto.TD_Weight;
                    model.TD_WeightA = dto.TD_WeightA;
                    model.TD_ReadCardIP = dto.TD_ReadCardIP;
                    model.TD_ShangWeiji = dto.TD_ShangWeiji;

                    data.success = await _DTSN_TongDaoServices.Update(model);

                    if (data.success)
                    {
                        data.msg = "更新成功";
                        data.response = dto.TD_ID.ObjToString();



                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "参数异常，您要更新的数据不存在";
                }
            }
            else
            {
                data.success = false;
                data.msg = "参数异常";
            }
            return data;
        }




        [HttpPost]
        [Route("/api/[controller]/Add")]
        public async Task<MessageModel<string>> Add(DTSN_TongDao dto)
        {
            var data = new MessageModel<string>();
            dto.TD_CreateTime = DateTime.Now;
            int id = await _DTSN_TongDaoServices.Add(dto);

            data.success = id > 0;
            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }
            return data;
        }




        [HttpDelete]
        [Route("/api/[controller]/Delete")]
        public async Task<MessageModel<string>> Delete(int id)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var userDetail = await _DTSN_TongDaoServices.QueryById(id);
                userDetail.TD_State = -1;
                data.success = await _DTSN_TongDaoServices.Update(userDetail);
                if (data.success)
                {
                    data.msg = "删除成功";
                    data.response = userDetail?.TD_ID.ObjToString();
                }
            }
            return data;
        }





        [HttpDelete]
        [Route("/api/[controller]/BatchDelete")]
        public async Task<MessageModel<string>> BatchDelete(string ids)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(ids))
            {

                {
                    #region 软删除

                    int[] list = Array.ConvertAll<string, int>(ids.Split(','), s => int.Parse(s));

                    DTSN_TongDao model = new DTSN_TongDao();
                    model.TD_State = -1;
                    string whereStr = " TD_ID in (" + ids + ")";
                    List<string> colList = new List<string>();
                    colList.Add("TD_State");
                    List<string> colHL = new List<string>();

                    bool isOK = await _DTSN_TongDaoServices.Update(model, colList, colHL, whereStr);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }

                    #endregion
                }
                if (false)
                {
                    #region 直接删除 

                    object[] list = Array.ConvertAll<string, object>(ids.Split(','), s => int.Parse(s));

                    bool isOK = await _DTSN_TongDaoServices.DeleteByIds(list);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }
                    #endregion
                }
            }
            return data;
        }


        [HttpGet]
        [Route("/api/[controller]/GetList")]
        [AllowAnonymous]
        public async Task<MessageModel<List<DTSN_TongDao>>> GetList(string key = "")
        {
            Expression<Func<DTSN_TongDao, bool>> whereExpression = Td => Td.TD_State > -1;
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            else
            {
                whereExpression = whereExpression.And(Td => Td.TD_Name.Contains(key) || Td.TD_Code.Contains(key));
            }

            string colOrder = " TD_Code asc ";

            var data = await _DTSN_TongDaoServices.Query(whereExpression, colOrder);

            return new MessageModel<List<DTSN_TongDao>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };
        }


    }
}

